/*
 * ping.h
 *
 *  Created on: 05.02.2013
 *      Author: aska
 */


#include <boost/asio.hpp>
#include <boost/bind.hpp>
//#include <boost/checks.hpp>
#include <istream>
#include <iostream>
#include <ostream>

#include "icmp_header.hpp"
#include "ipv4_header.hpp"

using boost::asio::ip::icmp;
using boost::asio::deadline_timer;
namespace posix_time = boost::posix_time;
using namespace std;

#ifndef PING_H_
#define PING_H_

class ping_storage
{
public:
	//boost::asio::io_service io_service_;
	char ping_addr_[63];
	int ping_result_;
	int ping_timeout_;
	ping_storage();
	int set_addr(char ping_addr[63]);
	int set_timeout(int ping_timeout);
	int run_once();
	//int * log_add_str(char * log_str);
};

class pinger
{
	icmp::resolver resolver_;
	icmp::endpoint destination_;
	icmp::socket socket_;
	deadline_timer timer_;
	unsigned short sequence_number_;
	posix_time::ptime time_sent_;
	boost::asio::streambuf reply_buffer_;
	std::size_t num_replies_;
public:
	int num_to_send_;
	int num_skipped_;
	int num_sended_;
	int ping_timeout_;
	int * ping_result_;
	char ping_addr_[63];
	boost::asio::io_service * io_service_;
public:
	//pinger();
	pinger(boost::asio::io_service& io_service, const char* destination, int ping_timeout, int * ping_result)
	//pinger(boost::asio::io_service& io_service, const char* destination)
		: resolver_(io_service), socket_(io_service, icmp::v4()),
		  timer_(io_service), sequence_number_(0), num_replies_(0),
		  num_skipped_(0), num_sended_(0), ping_timeout_(ping_timeout), ping_result_(ping_result)
	{
		//std::cout << " destination " << destination << " timeout " << ping_timeout << " timeout_ " << ping_timeout_ << std::endl;
		strcpy(ping_addr_, destination);
		io_service_ = &io_service;
		icmp::resolver::query query(icmp::v4(), destination, "");
		destination_ = *resolver_.resolve(query);
		start_send();
		start_receive();
	};
private:
	void start_send();
	void handle_timeout();
	void start_receive();
	void handle_receive(size_t length);
	static unsigned short get_identifier();
};

#endif /* PING_H_ */
